package com.gopay.bis.service.bank.go.impl;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.gopay.bis.service.bank.go.GoBankService;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.manager.order.CpsGeneralMainOrderQueryManager;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.pg.PgGenOrderTransDtl;
import com.gopay.common.exception.GopayException;
import com.gopay.common.gateway.manager.PgGeneralOrderTransDtlQueryManager;
import com.gopay.common.util.DateUtils;

/**
 * 
 * @GoBankServiceImpl.java
 * @author yaobo
 * @2012-12-10 下午5:45:57 www.gopay.com.cn Inc.All rights reserved.
 */
@Service("goBankService")
public class GoBankServiceImpl implements GoBankService {

    @Resource(name = "cpsGeneralMainOrderQueryManager")
    private CpsGeneralMainOrderQueryManager mainOrderQuery;

    @Resource(name = "pgGeneralOrderTransDtlQueryManager")
    private PgGeneralOrderTransDtlQueryManager orderTransDtlQuery;
    
    

    public BaseMessage buildSign(String orderId, String ip) throws GopayException {
        // 获取主订单表
        CpsGenMainOrder mainOrder = mainOrderQuery.get(orderId);
        if (null == mainOrder) {
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E5041);
        }
        
        // 获取网关流水
        PgGenOrderTransDtl orderTrans = orderTransDtlQuery.get(mainOrder.getTransDtlSq());

        BaseMessage base = new BaseMessage();

        base.setOrderId(orderId);
        base.setOrderDate(DateUtils.format(mainOrder.getCreatedTs()));
        /*base.setAmount(mainOrder.getTotalOrderAmt());
        if (mainOrder.getSettleAmt() != null) {
            // 发送银行金额取结算金额,若为空则取总金额字段
            base.setAmount(mainOrder.getSettleAmt());
        }*/
        // 若结算金额为空或0.00获取订单总金额, 若订单总金额为空或0.00获取商户交易金额
        if (mainOrder.getSettleAmt() != null && mainOrder.getSettleAmt().compareTo(BigDecimal.ZERO) != 0) {
            base.setAmount(mainOrder.getSettleAmt());
        } else if (mainOrder.getTotalOrderAmt() != null && mainOrder.getTotalOrderAmt().compareTo(BigDecimal.ZERO) != 0) {
            base.setAmount(mainOrder.getTotalOrderAmt());
        } else {
            base.setAmount(mainOrder.getMerTxnAmt());
        }
        
        base.setBank(mainOrder.getOutStlmId());
        base.setSupportCredit(true);
        base.setCustomerID(mainOrder.getMerId());
        if (orderTrans != null) {
            // 差额支付没有网关流水，需要判断
            base.setSpecial(orderTrans.getGoodsName());
        }
        base.setSpecial2(mainOrder.getMerId());
        base.setSpecial3(ip);
        base.setSpecial4(mainOrder.getGopayIntTxnCd()); // 内部交易码
        return base;
    }
}